<template>
  <div class="header">
    <img src="\icon\AI.png" alt="AI Icon" />
    <span>智能知识助手</span>
  </div>
  <div class="content" ref="contentRef">
    <div class="message">
      <ul v-if="isShowFunctipRef">
        <li v-if="!props.appkyes || props.appkyes?.includes('CHECK')">对当前编辑器知识 <el-button @click="doKnowTalk('内容校对')"
            style="margin-left: 8px;" type="success" icon="Check" round size="small">校对</el-button>
        </li>
        <li v-if="!props.appkyes || props.appkyes?.includes('TRANSLATE')">中英文互译 <el-button @click="doKnowTalk('中英文互译')"
            style="margin-left: 8px;" type="success" icon="Switch" round size="small">翻译</el-button>
        </li>
        <li v-if="!props.appkyes || props.appkyes?.includes('SUMMARIZE')">知识总结<el-button @click="doKnowTalk('解析内容')"
            style="margin-left: 8px;" type="success" icon="GobletSquareFull" round size="small">分析</el-button></li>
        <li v-if="!props.appkyes || props.appkyes?.includes('ABSTRACT')">获取知识<el-button @click="doKnowTalk('获取摘要')"
            style="margin-left: 8px;" type="success" icon="Postcard" round size="small">提取摘要</el-button></li>
            <li v-if="!props.appkyes || props.appkyes?.includes('goHome')">点击后返回首页<el-button @click="gotoHome()"
              style="margin-left: 8px;" type="success" icon="House" round size="small">返回首页</el-button></li>
      </ul>
      <ai_msg ref="aiMsgRef" :is-show-msg="true" :start-handle="sendMsgStartHandle" :end-handle="sendMsgEndHandle"
        :scroll-to-bottom="scrollToBottom"></ai_msg>
    </div>
  </div>
  <div class="footer">
    <div style="padding: 8px;padding-top: 0px;">
      <el-button type="success" :icon="resizeButtonIconRef" title="改变窗口大小" v-if="props.resizeHandle"
        @click="reSetAiBoxWidth()" circle size="small" />
      <el-button type="danger" icon="Delete" @click="clearTalk()" title="清空记录" circle size="small" />
      <el-button type="warning" @click="aiMsgRef.stopTalk()" v-if="showStopTalkButtonRef" icon="VideoPause"
        title="停止接收消息" circle size="small" />
      <el-button type="success" v-if="isShowInsertButtonRef && props.insertEditorHandle" size="small"
        @click="props.insertEditorHandle(getHtmlMsgs())" round>插入编辑器</el-button>
      <el-switch v-if="props.getTextHandle" style="float:right;" v-model="isQuotingDocRef" class="ml-2" width="80"
        inline-prompt active-text="当前知识" inactive-text="当前知识" />
      <el-switch style="float:right;margin-right: 4px;" v-model="isSearchKnowRef" class="ml-2" width="90" inline-prompt
        active-text="引用知识库" inactive-text="引用知识库" />
    </div>
    <div class="input-container">
      <input v-model="msg" class="skc-chart-input" placeholder="开始提问" @keyup="handleKeyup" />
      <el-button :type="sendButtonState.type" plain icon="ChatLineRound" @click="sendMsg()" loading-icon="ChatLineRound"
        :loading="sendButtonState.isLoading" round>{{ sendButtonState.title }}</el-button>
    </div>
    <div style="margin-top: 4px;color: #999999;"> Tip:发送消息组合键&nbsp;&nbsp;Ctrl+Enter&nbsp;&nbsp;</div>
  </div>
</template>
<script setup lang="ts">
import { nextTick, reactive, ref } from 'vue';
import ai_msg from './ai_msg.vue';
import type { TalkMsg } from '@/types/ai/TalkMsg';
import TurndownService from 'turndown';
import type { SendMsg } from '@/types/ai/SendMsg';
import farmRoutUtils from '@/hook/farmRoutUtils';

const gotoHome=()=>{
  farmRoutUtils.goToHome();
}

const isShowFunctipRef = ref(true)
const props = defineProps({
  resizeHandle: {
    type: Function,
    required: false,
  },
  insertEditorHandle: {
    type: Function,
    required: false,
  },
  getTextHandle: {
    type: Function,
    required: false,
  },
  appkyes: {
    type: Array,
    required: false,
  },
});
const isSearchKnowRef = ref(false)
const aiMsgRef = ref();
const isShowInsertButtonRef = ref(false);
const contentRef = ref<HTMLElement | null>(null);
const msg = ref('');
const resizeButtonIconRef = ref('ArrowLeft');
const showStopTalkButtonRef = ref(false);
const isQuotingDocRef = ref(true);

//------------------------------------------------------------------------------------------------
const aiBoxWidthMax = ref(true)


const clearTalk = () => {
  aiMsgRef.value.stopTalk()
  isShowFunctipRef.value = true;
  aiMsgRef.value.clearMsg()
}

const doKnowTalk = (instruction: string) => {
  isQuotingDocRef.value = true;
  msg.value = instruction;
  sendMsg();
}


/**
 * 获得所有对话消息
 */
const getHtmlMsgs = (): TalkMsg[] => {
  const msgs: TalkMsg[] = aiMsgRef.value.getHtmls();
  return msgs;
}

const reSetAiBoxWidth = () => {
  if (aiBoxWidthMax.value) {
    aiBoxWidthMax.value = false;
    props.resizeHandle!('650px');
    resizeButtonIconRef.value = 'ArrowRight';
  } else {
    aiBoxWidthMax.value = true;
    props.resizeHandle!('400px');
    resizeButtonIconRef.value = 'ArrowLeft';
  }
}

const sendButtonState = reactive({
  isLoading: false,
  title: '发送',
  type: 'success'
});

/**
 * 消息接收中。。
 */
const sendMsgStartHandle = () => {
  Object.assign(sendButtonState, {
    isLoading: true,
    title: '接收中...',
    type: 'info'
  })
  showStopTalkButtonRef.value = true;
  isShowInsertButtonRef.value = false;
  isShowFunctipRef.value = false;
  msg.value = '';
}
/**
 * 消息接收完毕
 */
const sendMsgEndHandle = () => {
  Object.assign(sendButtonState, {
    isLoading: false,
    title: '发送',
    type: 'success'
  })
  showStopTalkButtonRef.value = false;
  if (getHtmlMsgs().length >= 2) {
    isShowInsertButtonRef.value = true;
  } else {
    isShowInsertButtonRef.value = false;
  }
}

const handleKeyup = (event: KeyboardEvent) => {
  // 检测是否按下了 Ctrl+enter
  if (event.key === 'Enter' && (event.ctrlKey || event.metaKey)) {
    event.preventDefault(); // 阻止浏览器默认的行为 [ty-reference](14)
    sendMsg(); // 调用发送消息的方法
  }
};

/**
 * 发送消息到大模型
 */
const sendMsg = () => {
  if (!sendButtonState.isLoading && msg.value) {
    let knowText = '';
    if (props.getTextHandle && isQuotingDocRef.value) {
      knowText = props.getTextHandle!()
    }
    const turndownService = new TurndownService();
    knowText = (turndownService.turndown(knowText));
    const sendMsg = {
      msg: msg.value,
      quotingText: knowText,
      searchKnow: isSearchKnowRef.value ? "all" : "no",
      msgType: "QUESTION_ANSWERING",
    } as SendMsg;
    aiMsgRef.value.senMsg(sendMsg);
  }
}
/**
 * 发送消息到大模型
 */
const sendMsgByMsg = (msg: SendMsg) => {
  msg.searchKnow = isSearchKnowRef.value ? "all" : "no";
  aiMsgRef.value.senMsg(msg);
}
/**
 * 获得当前会话key
 */
const getTalkHtml = () => {
  return aiMsgRef.value.getHtmls() as TalkMsg[];
}

const scrollToBottom = () => {
  nextTick(() => {
    if (contentRef.value) {
      contentRef.value.scrollTop = contentRef.value.scrollHeight;
    } else {
      console.warn('Content element is not available.');
    }
  });
};
//------------------------------------------------------------------------------------------------
defineExpose({ sendMsgByMsg, getTalkHtml })


</script>

<style scoped>
/* 全局样式 */
.header {
  padding: 20px;
  font-size: 18px;
  display: flex;
  align-items: center;
  color: #555555;
  font-weight: 700;
}

.header img {
  height: 32px;
  width: 32px;
  margin-right: 20px;
}

.content {
  height: calc(100vh - 210px);
  border-radius: 1em;
  background-color: #ffffff;
  margin: 20px;
  margin-bottom: 0px;
  margin-top: 0px;
  overflow: auto;
}

.content .message {
  color: #999999;
  font-size: 14px;
}

.content ul {
  margin-left: -10px;
  line-height: 3em;
  padding-top: 20px;
}

.footer {
  font-size: 12px;
  padding: 20px;
  padding-bottom: 10px;
}

.input-container {
  display: flex;
  align-items: center;
  background-color: #ffffff;
  border: 1px solid #dddddd;
  border-radius: 8px 22px 22px 8px;
  padding: 10px;
}

.skc-chart-input {
  border: none !important;
  outline: none !important;
  resize: none;
  color: #555555;
  width: 100%;
}

.skc-chart-input:focus {
  border-color: transparent !important;
}
</style>
